import common from '@/common/common.js';
//多语言的导入
import zhcn from "@/common/language/zh-cn.js";
import english from "@/common/language/english.js";

import Vue from 'vue'
import ElementUI from 'element-ui'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import configPartial from '@/Partial/configPartial.js';
import configAuto from '@/Auto/configAuto.js';

//主网站域名
let webapiUrl = configPartial.webapiUrl;
let ajaxErrorUrl = configPartial.ajaxErrorUrl;
//console.log("webapiUrl", webapiUrl);
let recordError = configPartial.recordError;
let errorAction = configPartial.errorAction;
let loginUrl = configPartial.loginUrl;
let tokenKey = configPartial.tokenKey; //尽量全小写,因为某些andriod的浏览器会转换为全小写的
let wechatTokenKey = configPartial.wechatTokenKey; //微信的token值
let testOpenID = configPartial.testOpenID; //测试OpenID
let tokenIsCookie = configPartial.tokenIsCookie; //是否是cookie存的
let loginWithPicValidate = configPartial.loginWithPicValidate; //登录是否带图片验证
let showLanguage = configPartial.showLanguage; //是否显示多语言切换
let websocketChatPort = configPartial.websocketChatPort; //webSocket端口

let autoLogin = configPartial.autoLogin; //自动给予一个token值
let themeName = configPartial.themeName;
let routeName = configPartial.routeName;
let langName = configPartial.langName;
let buttonName = configPartial.buttonName;

//混入common.baseVM的相关页面,created调用的初始化方法
const commonBaseVMInit = function (self) {
	//console.log(self.$route.path, self._uid);
	if (self.button != null) { //隐藏按钮
		var buttons = self.$store.state.tabsBar.buttons;
		var path = self.routePath;
		for (var i = 0; i < buttons.length; i++) {
			var item = buttons[i];
			if (item.Path == path) {
				var list = item.ButtonPowerSon;
				for (var j = 0; j < list.length; j++) {
					var btn = list[j];
					self.button[btn.ButtonName] = btn.Has;
				}
				break;
			}
		}
	}
}

var setTimeoutObj = null;
//ajax请求判断
const commonAjaxSuccess = function (data) {
	if (typeof (data) == "string") {
		try {
			data = JSON.parse(data);
		} catch (e) {
			return false;
		}
	}
	if (data.Total == -9100) { //WebChatToken错误
		common.setWechatToken("");
		common.getApp().$store.dispatch('setUser', "");
		location.reload();
		return false;
	}
	if (data.Total == -9110) { //微信Code异常
		common.setWechatToken("");
		common.getApp().$store.dispatch('setUser', "");
		common.getAuthorizeUrl(window.location.origin);
		return false;
	}
	if (data.Total == -9300 || data.Total == -9310) { //Token错误=-9300,帐号过期=-9310
		if (setTimeoutObj != null) {
			clearTimeout(setTimeoutObj);
			setTimeoutObj = null;
		}
		setTimeoutObj = setTimeout(() => {
			common.showMsg(data.Message, () => {
				common.getApp().$store.dispatch('setUser', "");
				goToLogin();
			});
			setTimeoutObj = null;
		}, 1000);
		return false;
	}

	if (data.Total == -9700) { //WeChatToken登录信息
		var info = data.Result[0];
		loginSetInfo(info);
		return false;
	}
	if (data.Total == -9710) { //用户信息及权限重新加载
		common.showToast(data.Message, "success");
		loginByToken();
		return false;
	}
	if ((!data.Success && !!data.Message && data.Total == 0) || data.Total == -9000) { //验证不通过或异常信息
		common.showToast({
			message: data.Message,
			type: 'error'
		});
		return false;
	}
	return true;
}

function goToLogin() {
	var app = common.getApp();
	if (app.$route.path == loginUrl) {
		return;
	}
	loginOut();
}

function loginByToken() {
	common.tool.post("api/Login/LoginByToken", {}).then(data => {
		setTimeout(() => {
			var info = data.Result;
			loginSetInfo(info);
		});
	});
}

const getLanguageJs = function () {
	return storeObj.state.language.js;
}

function setLanguageObj(lang) {
	if (lang == "zh-cn") {
		storeObj.state.language = zhcn;
		Vue.use(ElementUI, {
			size: "small",
			locale: zhLocale
		});
	} else if (lang == "english") {
		storeObj.state.language = english;
		Vue.use(ElementUI, {
			size: "small",
			locale: enLocale
		});
	} else {
		Vue.use(ElementUI, {
			size: "small",
		});
	}
	var language = storeObj.state.language;
	storeObj.state.projectName = language.projectName;
	storeObj.state.shortName = language.shortName;
	storeObj.state.compnay = language.compnay;
	//路由的改变
	window.Vue.nextTick(() => {
		//重置路由的名称,从开发名称改变
		var list = common.getApp().$router.options.routes;
		languageChangeRouteName(list);
		//存入了的路由,也做一次改变
		let route = common.tool.getItem(routeName);
		if (!!route) {
			var jsonTemp = JSON.parse(route);
			languageChangeRouteName(jsonTemp);
			storeObj.state.tabsBar.routes = jsonTemp;
		}
		//elementui的多语言切换;直接刷新页面来加载
	});
}

//改变成多语言
var languageChangeRouteName = function (list) {
	if (list == null) return;
	var lan = storeObj.state.language["$router"];
	if (lan == null) return;
	for (var i = 0; i < list.length; i++) {
		var item = list[i];
		if (item.meta != null && item.meta.title != null) {
			var val = lan[item.meta.title];
			if (val != null && val != "") {
				item.meta.title = val;
			}
		}
		if (item.children != null) {
			languageChangeRouteName(item.children);
		}
	}
}

//main.js调用的最早初始化
const init = function (callback) {
	var scriptDom = document.getElementById("enumScriptId");
	scriptDom.src = webapiUrl + "/api/Login/GetAllEnum";
	scriptDom.onload = function () {
	};
	var token = storeObj.state.user.token;
	if (token == null || token == "") {
		var val = common.getToken();
		var json = null;
		if (!!val) {
			try {
				json = JSON.parse(val);
				//console.log(json);
				if (!!json.createDate) {
					var before = common.tool.format(new Date(json.createDate), 'yyyy-MM-dd');
					var now = common.tool.format(new Date(), 'yyyy-MM-dd');
					if (before != now) {
						json = null;
					}
				}
			} catch (e) {
				json = null;
			}
		}
		if (json != null) {
			storeObj.state.user = json;
		} else { //没有token值
			if (autoLogin) {
				var temp = Object.assign(JSON.parse(JSON.stringify(storeObj.state.user)), {
					token: "123456",
					userName: "演示帐号"
				});
				console.log("自动登录token赋值");
				common.setToken(temp);
				val = common.getToken();
				storeObj.state.user = JSON.parse(val);
				common.tool.setItem(routeName, testRoutes);
			}
		}
	}

	let theme = common.tool.getItem(themeName);
	if (!!theme) {
		storeObj.state.theme = Object.assign(storeObj.state.theme, JSON.parse(theme));
	}
	let showHelper = common.tool.getItem("showHelper");
	if (!!showHelper) {
		storeObj.state.showHelper = showHelper.toLowerCase() == "true";
	} else {
		storeObj.state.showHelper = false;
	}
	let device = common.tool.handleIsMobile();
	storeObj.state.settings.device = device ? "mobile" : "desktop";

	//多语言的加载
	let lang = common.tool.getItem(langName);
	if (!!lang) {
		storeObj.state.lang = lang;
	} else {
		lang = "zh-cn";
	}
	setLanguageObj(lang);

	//加载button
	let buttons = common.tool.getItem(buttonName);
	if (!!buttons) {
		var jsonTemp = JSON.parse(buttons);
		storeObj.state.tabsBar.buttons = jsonTemp;
	}
}

//appVue.created调用
const appVueCreated = function (self) {
	$(function () {
		//加载特效层JS代码
		let preLoder = $("#preloader");
		preLoder.fadeOut(300);
	});

	common.getDeviceId();
}

const routerBeforeEach = function (to, from, next) {
	//console.log("router.beforeEach", to, from, next);
	//next();
	//return;
	if (storeObj.state.user.token && (to.path == "/" || to.path == loginUrl)) {
		next({
			path: "/pages/index"
		});
		return;
	}
	if (!!storeObj.state.user.token || to.path == loginUrl || to.path == '/401' || to.path == '/404') {
		next();
		return;
	}
	next({
		path: loginUrl,
		query: {
			redirect: to.fullPath
		}
	});
}

var deepClone = function (target) {
	var hasOwnProperty = Object.prototype.hasOwnProperty;
	var propIsEnumerable = Object.prototype.propertyIsEnumerable;

	function isObj(x) {
		var type = typeof x;
		return x !== null && (type === 'object' || type === 'function');
	}

	function toObject(val) {
		if (val === null || val === undefined) {
			throw new TypeError('Cannot convert undefined or null to object');
		}
		return Object(val);
	}

	function assignKey(to, from, key) {
		var val = from[key];
		if (val === undefined || val === null) {
			return;
		}
		if (hasOwnProperty.call(to, key)) {
			if (to[key] === undefined || to[key] === null) {
				throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
			}
		}
		if (!hasOwnProperty.call(to, key) || !isObj(val)) {
			to[key] = val;
		} else {
			to[key] = assign(Object(to[key]), from[key]);
		}
	}

	function assign(to, from) {
		if (to === from) {
			return to;
		}
		from = Object(from);
		for (var key in from) {
			if (hasOwnProperty.call(from, key)) {
				assignKey(to, from, key);
			}
		}
		if (Object.getOwnPropertySymbols) {
			var symbols = Object.getOwnPropertySymbols(from);

			for (var i = 0; i < symbols.length; i++) {
				if (propIsEnumerable.call(from, symbols[i])) {
					assignKey(to, from, symbols[i]);
				}
			}
		}
		return to;
	}

	target = toObject(target);
	for (var s = 1; s < arguments.length; s++) {
		assign(target, arguments[s]);
	}
	return target;
}

const storeObjTemp = {
	state: { //要设置的全局访问的state对象
		projectName: '',
		shortName: '',
		compnay: '',
		lang: 'zh-cn', //语言
		language: {}, //语言对象
		showHelper: false,
		user: {
			token: "",
			userName: "",
			userHeader: "",
			createDate: new Date(),
			canSeePhone: false,
			isAdminStore: false,
			isMainStore: false,
			sysEmployeeID: 0,
			sysStoreID: 0,
			isDemo: false
		},
		recordRoute: true,

		theme: {
			name: "default",
			//是否国定头部 固定fixed 不固定noFixed
			header: 'fixed',
			//横纵布局 horizontal 横向 vertical 纵向的
			layout: 'horizontal',
			//是否开启主题配置按钮
			themeBar: true,
			//是否显示多标签页
			tabsBar: true,
			//是否记录新增值
			recordValue: true,
		},
		tabsBar: {
			visitedRoutes: [],
			routes: [],
			buttons: []
		},
		settings: {
			device: "desktop", //desktop,mobile
			collapse: false,
			logo: "vuejs-fill"
		},

		errorLogs: []
	},
	getters: { //实时监听state值的变化(最新状态)
		projectName: state => state.projectName,
		shortName: state => state.shortName,
		compnay: (state) => state.compnay,
		recordRoute: (state) => state.recordRoute,
		lang: (state) => state.lang,
		language: (state) => state.language,
		showHelper: (state) => state.showHelper,

		user: (state) => state.user,
		theme: (state) => state.theme,
		tabsBar: (state) => state.tabsBar,
		settings: (state) => state.settings,
		errorLogs: (state) => state.errorLogs,
	},
	mutations: {
		setUser(state, val) {
			common.setToken(val);
			state.user = (val == null || val == "") ? {} : Object.assign(state.user, val);
		},
		setLang(state, val) {
			common.tool.setItem(langName, val);
			state.lang = val;
			//更改语言对象
			setLanguageObj(state.lang);
		},
		setLanguage(state, val) {
			state.language = val;
		},
		setShowHelper(state, val) {
			common.tool.setItem("showHelper", val);
			state.showHelper = val;
		},
		setTheme(state, val) {
			common.tool.setItem(themeName, val);
			state.theme = val;
		},
		setSettings(state, val) {
			state.settings = val;
		},
		setErrorLogs(state, val) {
			state.errorLogs.push(val);
		},
		clearErrorLogs(state, val) {
			state.errorLogs = [];
		},

		setRoutes(state, val) {
			var before = JSON.parse(JSON.stringify(val));
			languageChangeRouteName(val);
			state.tabsBar.routes = val;
			common.tool.setItem(routeName, before);
		},
		setButtons(state, val) {
			state.tabsBar.buttons = val;
			common.tool.setItem(buttonName, val);
		},
		foldSideBar: (state) => {
			state.settings.collapse = true;
		},
		openSideBar: (state) => {
			state.settings.collapse = false
		},
		changeCollapse: (state) => {
			state.settings.collapse = !state.settings.collapse
		},
		addVisitedRoute(state, route) {
			let target = state.tabsBar.visitedRoutes.find((item) => item.path === route.path)
			if (target) {
				if (route.fullPath !== target.fullPath) Object.assign(target, route)
				return
			}
			state.tabsBar.visitedRoutes.push(Object.assign({}, route))
		},
		delVisitedRoute(state, route) {
			state.tabsBar.visitedRoutes.forEach((item, index) => {
				if (item.path === route.path) {
					state.tabsBar.visitedRoutes.splice(index, 1)
				}
			})
		},
		delOthersVisitedRoute(state, route) {
			state.tabsBar.visitedRoutes = state.tabsBar.visitedRoutes.filter(
				(item) => item.meta.affix || item.path === route.path
			)
		},
		delLeftVisitedRoute(state, route) {
			let index = state.tabsBar.visitedRoutes.length
			state.tabsBar.visitedRoutes = state.tabsBar.visitedRoutes.filter((item) => {
				if (item.name === route.name) index = state.tabsBar.visitedRoutes.indexOf(item)
				return item.meta.affix || index <= state.tabsBar.visitedRoutes.indexOf(item)
			})
		},
		delRightVisitedRoute(state, route) {
			let index = state.tabsBar.visitedRoutes.length
			state.tabsBar.visitedRoutes = state.tabsBar.visitedRoutes.filter((item) => {
				if (item.name === route.name) index = state.tabsBar.visitedRoutes.indexOf(item)
				return item.meta.affix || index >= state.tabsBar.visitedRoutes.indexOf(item)
			})
		},
		delAllVisitedRoutes(state) {
			state.tabsBar.visitedRoutes = state.tabsBar.visitedRoutes.filter((item) => item.meta.affix)
		},
		updateVisitedRoute(state, route) {
			state.tabsBar.visitedRoutes.forEach((item) => {
				if (item.path === route.path) item = Object.assign(item, route)
			})
		},
	},

	actions: {
		setUser(context, val) {
			context.commit('setUser', val);
		},
		setLang(context, val) {
			context.commit('setLang', val);
		},
		setLanguage(context, val) {
			context.commit('setLanguage', val);
		},
		setShowHelper(context, val) {
			context.commit('setShowHelper', val);
		},
		setTheme(context, val) {
			context.commit('setTheme', val);
		},
		setSettings(context, val) {
			context.commit('setSettings', val);
		},
		setErrorLogs(context, val) {
			context.commit('setErrorLogs', val);
		},
		clearErrorLogs(context, val) {
			context.commit('clearErrorLogs', val);
		},

		setRoutes(context, val) {
			context.commit('setRoutes', val);
		},
		setButtons(context, val) {
			context.commit('setButtons', val);
		},
		openSideBar(context, val) {
			context.commit('openSideBar')
		},
		foldSideBar(context, val) {
			context.commit('foldSideBar')
		},
		changeCollapse: (context, val) => {
			context.commit('changeCollapse')
		},
		addVisitedRoute({
			commit
		}, route) {
			commit('addVisitedRoute', route)
		},
		async delRoute({
			dispatch,
			state
		}, route) {
			await dispatch('delVisitedRoute', route)
			return {
				visitedRoutes: [...state.tabsBar.visitedRoutes],
			}
		},
		delVisitedRoute({
			commit,
			state
		}, route) {
			commit('delVisitedRoute', route)
			return [...state.tabsBar.visitedRoutes]
		},
		async delOthersRoutes({
			dispatch,
			state
		}, route) {
			await dispatch('delOthersVisitedRoute', route)
			return {
				visitedRoutes: [...state.tabsBar.visitedRoutes],
			}
		},
		async delLeftRoutes({
			dispatch,
			state
		}, route) {
			await dispatch('delLeftVisitedRoute', route)
			return {
				visitedRoutes: [...state.tabsBar.visitedRoutes],
			}
		},
		async delRightRoutes({
			dispatch,
			state
		}, route) {
			await dispatch('delRightVisitedRoute', route)
			return {
				visitedRoutes: [...state.tabsBar.visitedRoutes],
			}
		},
		delOthersVisitedRoute({
			commit,
			state
		}, route) {
			commit('delOthersVisitedRoute', route)
			return [...state.tabsBar.visitedRoutes]
		},
		delLeftVisitedRoute({
			commit,
			state
		}, route) {
			commit('delLeftVisitedRoute', route)
			return [...state.tabsBar.visitedRoutes]
		},
		delRightVisitedRoute({
			commit,
			state
		}, route) {
			commit('delRightVisitedRoute', route)
			return [...state.tabsBar.visitedRoutes]
		},
		async delAllRoutes({
			dispatch,
			state
		}, route) {
			await dispatch('delAllVisitedRoutes', route)
			return {
				visitedRoutes: [...state.tabsBar.visitedRoutes],
			}
		},
		delAllVisitedRoutes({
			commit,
			state
		}) {
			commit('delAllVisitedRoutes')
			return [...state.tabsBar.visitedRoutes]
		},
		updateVisitedRoute({
			commit
		}, route) {
			commit('updateVisitedRoute', route)
		},
	}
}
//Object.assign(storeObjTemp, configPartial.storeObj);潜复制
var storeObj = deepClone(storeObjTemp, configPartial.storeObj);

import main from '@/pages/common/main.vue';
import blank from '@/pages/common/blank.vue';
const routerRoutesTemp = [{
	path: '/',
	redirect: loginUrl
}, { // 登录
	path: loginUrl,
	name: "登录",
	component: () => import('@/pages/login.vue')
},
{
	path: '/401',
	name: 'Page401',
	component: () => import('@/pages/common/401.vue'),
	hidden: false,
},
{
	path: '/404',
	name: 'Page404',
	component: () => import('@/pages/common/404.vue'),
	hidden: false,
},
{
	path: '*',
	redirect: '/404',
	hidden: true,
},
{
	path: "/pages",
	name: "/pages",
	redirect: '/pages/index',
	component: main,
	children: [{
		path: 'index',
		name: 'index', //页面name不是此,则不缓存
		component: () => import('@/pages/index.vue'),
		meta: {
			title: '首页',
			remixIcon: 'home-line',
			affix: true,
		},
	},
	{
		path: 'index2',
		name: 'index2', //页面name不是此,则不缓存
		component: () => import('@/pages/common/index2.vue'),
		meta: {
			title: '首页2',
			remixIcon: 'home-line',
			affix: true,
		},
	},
	{
		path: '401',
		name: 'Error401',
		component: () => import('@/pages/common/401.vue'),
		meta: {
			title: '401'
		},
	},
	{
		path: '404',
		name: 'Error404',
		component: () => import('@/pages/common/404.vue'),
		meta: {
			title: '404'
		},
	},
	{
		path: 'icon',
		component: blank,
		//redirect: 'noRedirect',
		name: 'icon',
		meta: {
			title: '图标'
		},
		children: [{
			path: 'awesomeIcon',
			name: 'awesomeIcon',
			component: () => import('@/pages/common/icon/awesomeIcon.vue'),
			meta: {
				title: '常规图标'
			},
		},
		{
			path: 'colorfulIcon',
			name: 'colorfulIcon',
			component: () => import('@/pages/common/icon/colorfulIcon.vue'),
			meta: {
				title: '多彩图标'
			},
		},
		],
	},
	{
		path: 'test',
		name: 'test',
		component: () => import('@/pages/system/test.vue'),
		meta: {
			title: '相关功能页面'
		}
	}
	]
},
//新加路由Start

//新加路由End
{
	path: '/System',
	component: main,
	redirect: 'noRedict',
	name: 'System',
	meta: {
		title: '系统'
	},
	children: [{
		path: 'SysDicList',
		name: 'SysDicList',
		component: () => import('@/System/SysDicList.vue'),
		meta: {
			title: '数据字典'
		},
	}, {
		path: 'SysSettingList',
		name: 'SysSettingList',
		component: () => import('@/System/SysSettingList.vue'),
		meta: {
			title: '系统参数'
		},
	}, {
		path: 'SysStoreList',
		name: 'SysStoreList',
		component: () => import('@/System/Partial/SysStore/SysStoreList.vue'),
		meta: {
			title: '店铺管理'
		},
	}, {
		path: 'SysFileList',
		component: () => import('@/System/SysFileList.vue'),
		name: 'SysFileList',
		meta: {
			title: '附件管理'
		}
	}, {
		path: 'SysStoreAdd',
		name: 'SysStoreAdd',
		component: () => import('@/System/Partial/SysStore/SysStoreAdd.vue'),
		meta: {
			title: '店铺新建/编辑'
		},
	}, {
		path: 'SysStoreAddRedict',
		name: 'SysStoreAddRedict',
		component: () => import('@/System/Partial/SysStore/SysStoreAddRedict.vue'),
		meta: {
			title: '店铺新建/编辑'
		},
	}, {
		path: 'SysEmployeeList',
		name: 'SysEmployeeList',
		component: () => import('@/System/SysEmployeeList.vue'),
		meta: {
			title: '系统员工管理'
		},
	}, {
		path: 'SysRolePostList',
		name: 'SysRolePostList',
		component: () => import('@/System/SysRolePostList.vue'),
		meta: {
			title: '权限角色管理'
		},
	}, {
		path: 'SysFeedbackList',
		name: 'SysFeedbackList',
		component: () => import('@/System/SysFeedbackList.vue'),
		meta: {
			title: '问题反馈'
		},
	}, {
		path: 'SysStatisticalSqlList',
		name: 'SysStatisticalSqlList',
		component: () => import('@/System/SysStatisticalSqlList.vue'),
		meta: {
			title: '特殊导出'
		}
	}, {
		path: 'Weixin',
		name: 'Weixin',
		component: () => import('@/System/Weixin.vue'),
		meta: {
			title: '微信公众号'
		}
	}, {
		path: 'WeixinMini',
		name: 'WeixinMini',
		component: () => import('@/System/WeixinMini.vue'),
		meta: {
			title: '微信小程序'
		}
	}, {
		path: 'WeixinPc',
		name: 'WeixinPc',
		component: () => import('@/System/WeixinPc.vue'),
		meta: {
			title: '微信PC后台'
		}
	}]
},
{
	path: '/System/SysFileListChoice',
	component: () => import('@/System/SysFileListChoice.vue'),
	name: '/System/SysFileListChoice',
	meta: {
		title: '选择附件'
	}
},
{
	path: '/pagesX',
	name: "组件1",
	component: main,
	redirect: 'noRedict',
	children: [{
		path: 'table',
		name: 'Table', //vue页面里,那么不是Table,则不会缓存
		component: () => import('@/pagesX/table.vue'),
		meta: {
			title: '表格'
		},
	},
	{
		path: 'form',
		name: 'Form',
		component: () => import('@/pagesX/form.vue'),
		meta: {
			title: '表单'
		},
	},
	{
		path: 'pay',
		name: 'Pay',
		component: () => import('@/pagesX/pay.vue'),
		meta: {
			title: '流程控件'
		},
	}
	],
},
{
	path: '/pagesY',
	name: "组件2",
	component: main,
	redirect: 'noRedict',
	children: [{
		path: 'markdownEditor',
		name: 'MarkdownEditor',
		component: () => import('@/pagesY/markdownEditor.vue'),
		meta: {
			title: 'markdown编辑器'
		},
	},
	{
		path: 'editor',
		name: 'Editor',
		component: () => import('@/pagesY/editor.vue'),
		meta: {
			title: '富文本编辑器',
			badge: 'New',
		},
	},
	{
		path: 'log',
		name: 'Log',
		component: () => import('@/pagesY/errorLog.vue'),
		meta: {
			title: '错误日志模拟'
		},
	}
	],
}
];
var routerRoutes = configAuto.routerRoutes != null ? routerRoutesTemp.concat(configAuto.routerRoutes) :
	routerRoutesTemp;

//测试菜单数据
const testRoutes = [{
	path: '/pages',
	name: '/pages',
	children: [{
		path: 'index',
		name: 'index',
		meta: {
			title: '首页',
			remixIcon: 'home-line',
			affix: true,
		}
	}]
},
{
	path: '/pagesX',
	name: '/pagesX',
	meta: {
		title: '组件',
		remixIcon: 'folder-open-line'
	},
	children: [{
		path: 'table',
		name: 'Table',
		meta: {
			title: '表格'
		},
	},
	{
		path: 'form',
		name: 'Form',
		meta: {
			title: '表单'
		},
	},
	{
		path: 'pay',
		name: 'Pay',
		meta: {
			title: '流程控件'
		},
	}
	],
},
{
	path: '/pagesY',
	name: '/pagesY',
	meta: {
		title: '组件2',
		remixIcon: 'folder-open-line'
	},
	children: [{
		path: 'markdownEditor',
		name: 'MarkdownEditor',
		meta: {
			title: 'markdown编辑器'
		},
	},
	{
		path: 'editor',
		name: 'Editor',
		meta: {
			title: '富文本编辑器',
			badge: 'New',
		},
	},
	{
		path: 'log',
		name: 'Log',
		meta: {
			title: '错误日志模拟'
		},
	},
	{
		path: 'https://www.scmrrj.com/',
		name: 'https://www.scmrrj.com/',
		meta: {
			title: '官网外链',
			target: '_blank',
			//permissions: ['admin', 'editor'],
			badge: 'New',
		},
	},
	],
},
{
	path: 'pages',
	name: 'pages',
	meta: {
		title: '错误页',
		remixIcon: 'bug-line'
	},
	children: [{
		path: 'test',
		name: 'test',
		meta: {
			title: '相关功能页面'
		},
	},
	{
		path: 'icon',
		name: 'icon',
		meta: {
			title: '图标'
		},
		children: [{
			path: 'awesomeIcon',
			name: 'awesomeIcon',
			meta: {
				title: '常规图标'
			},
		},
		{
			path: 'colorfulIcon',
			name: 'colorfulIcon',
			meta: {
				title: '多彩图标'
			},
		},
		],
	},
	{
		path: '401',
		name: 'Error401',
		meta: {
			title: '401'
		},
	},
	{
		path: '404',
		name: 'Error404',
		meta: {
			title: '404'
		},
	},
	],
},
]

function replaceOrAddObj(n, o) {
	for (var item in n) {
		if (item == "children") continue;
		o[item] = n[item];
	}
	return o;
}

//删除name相同的
function replaceOrAddDel(arr, replaceOrAddArr) {
	for (var i = 0; i < replaceOrAddArr.length; i++) {
		var rAItem = replaceOrAddArr[i];
		if (rAItem.name == null || rAItem.children == null || rAItem.children.length == 0) continue;
		for (var x = 0; x < rAItem.children.length; x++) {
			var sItem = rAItem.children[x];
			var has = false;
			for (var j = 0; j < arr.length; j++) {
				var item = arr[j];
				if (item.name == null || item.children == null || item.children.length == 0) continue;
				for (var k = 0; k < item.children.length; k++) {
					var kItem = item.children[k];
					if (kItem.name == sItem.name) {
						item.children.splice(k, 1);
						has = true;
						break;
					}
				}
				if (has) {
					break;
				}
			}
		}
	}
	return arr;
}

function replaceOrAddBase(arr, replaceOrAddArr) {
	if (replaceOrAddArr == null || replaceOrAddArr.length == 0) return arr;
	//替换or新增
	for (var i = 0; i < replaceOrAddArr.length; i++) {
		var rAItem = replaceOrAddArr[i];
		var hasObj = null;
		if (rAItem.name != null) {
			for (var j = 0; j < arr.length; j++) {
				var item = arr[j];
				if (item.name == null) continue;
				if (item.name == rAItem.name) {
					hasObj = item;
					//有的情况,就修改
					item = replaceOrAddObj(rAItem, item);
					if (rAItem.children == null || rAItem.children.length == 0) {
						break;
					}
					if (item.children == null) item.children = [];
					//递归一下下一级路由
					item.children = replaceOrAddBase(item.children, rAItem.children);
					break;
				}
			}
		}
		if (hasObj == null) {
			arr.push(rAItem);
		}
	}
	return arr;
}

function replaceOrAdd(arr, replaceOrAddArr) {
	arr = replaceOrAddDel(arr, replaceOrAddArr);
	arr = replaceOrAddBase(arr, replaceOrAddArr);
	return arr;
}

routerRoutes = replaceOrAdd(routerRoutes, configPartial.routerRoutes);
// console.log(routerRoutes);
// setTimeout(() => {
//     storeObj.state.tabsBar.routes = testRoutes;
// }, 1000);

const goToNoLogin = function (path) {
	var app = common.getApp();
	var path = !!path ? path : app.$route.path;
	if (path == "/" || path == loginUrl) {
		var redirect = app.$route.query.redirect;
		var goToPage = !!redirect ? redirect : "/pages/index";
		common.tool.navigateTo(goToPage);
	} else {
		location.reload();
	}
}

const loginSetInfo = function (info) {
	//首页路由加入
	var index = testRoutes[0];
	var filter = info.Route.filter(item => {
		return item.path == index.path;
	});
	var route = [];
	if (filter.length > 0) {
		filter[0].children = index.children.concat(filter[0].children);
		route = info.Route;
	} else {
		route = [index].concat(info.Route);
	}
	//保存
	app.$store.dispatch("setRoutes", route);
	app.$store.dispatch("setButtons", info.ButtonPower);
	var user = Object.assign(storeObj.state.user, {
		token: info.Token,
		userName: info.UserName,
		userHeader: info.UserHeader,
		createDate: common.tool.format(new Date()),

		canSeePhone: info.CanSeePhone,
		isAdminStore: info.IsAdminStore,
		isMainStore: info.IsMainStore,
		sysEmployeeID: info.SysEmployeeID,
		sysStoreID: info.SysStoreID,
		isDemo: info.IsDemo
	});
	user.userHeader = common.tool.commonUrl(user.userHeader);
	app.$store.dispatch("setUser", user);

	goToNoLogin();
}

const loginOut = function () {
	common.tool.post('/api/Login/LoginOut').then((data) => {
		//console.log("注销", data);
	});
	var app = common.getApp();
	app.$store.dispatch("setUser", "");
	app.$store.dispatch("setRoutes", "");
	app.$store.dispatch("setButtons", "");
	app.$store.dispatch("delAllVisitedRoutes");
	app.$router.push({
		path: loginUrl,
		query: {
			redirect: app.$route.fullPath
		}
	});
}

export default {
	webapiUrl,
	loginUrl,
	tokenKey,
	wechatTokenKey,
	testOpenID,
	tokenIsCookie,
	loginWithPicValidate,
	ajaxErrorUrl,
	recordError,
	errorAction,
	websocketChatPort,

	loginSetInfo,
	loginOut,
	showLanguage,
	getLanguageJs,

	init,
	appVueCreated,
	commonBaseVMInit,
	commonAjaxSuccess,
	routerBeforeEach,
	routerRoutes,
	testRoutes,
	storeObj,

	loginByToken
}
